package com.jia.train.gateway.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


public class JwtTokenUtil {

    public static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);
    // 盐值
    private static final String KEY = "TimeWork";

    private static final String TOKEN_PREFIX = "Bearer ";

    public static String createToken(Long id, String mobile) {
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, 24);
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        // 身份信息
        payload.put("id", id);
        payload.put("mobile", mobile);

        String token = JWTUtil.createToken(payload, KEY.getBytes(StandardCharsets.UTF_8));
        logger.info("生成JWT token:{}", token);
        return TOKEN_PREFIX + token;
    }


    public static boolean validateToken(String bearerToken) {
        boolean validate = false;
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            // 去掉 "Bearer " 前缀，获取纯 JWT 字符串
            String token = bearerToken.substring(7);
            JWT jwt = JWTUtil.parseToken(token).setKey(KEY.getBytes(StandardCharsets.UTF_8));
            validate = jwt.validate(0);
        }
        logger.info("JWT token校验结果：{}", validate);
        return validate;
    }

    public static JSONObject getAuthentication(String bearerToken) {
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            // 去掉 "Bearer " 前缀，获取纯 JWT 字符串
            String token = bearerToken.substring(7);
            JWT jwt = JWTUtil.parseToken(token).setKey(KEY.getBytes(StandardCharsets.UTF_8));
            JSONObject payloads = jwt.getPayloads();
            payloads.remove(JWTPayload.ISSUED_AT);
            payloads.remove(JWTPayload.EXPIRES_AT);
            payloads.remove(JWTPayload.NOT_BEFORE);
            logger.info("获取Token用户信息:{}", payloads);
            return payloads;
        }
        return null;
    }

    public static void main(String[] args) {
        String bearerToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE3NjA5NTMzODQsIm1vYmlsZSI6IjEzMDk3NjgxMjY4IiwiaWQiOjE5NzkwODg5OTc5ODA1NzM2OTYsImV4cCI6MTc2MTAzOTc4NCwiaWF0IjoxNzYwOTUzMzg0fQ.6Ii9vp2cqyXcF5FQ4C-PX1G5bvhe4EGCig8gyeHLomE";
        JSONObject authentication = getAuthentication(bearerToken);
        System.out.println(validateToken(bearerToken));
        System.out.println(authentication);

    }


}
